import axios from "axios"
import router from "../../router"
import { ElMessage } from 'element-plus'

const isPro = Object.is(process.env.NODE_ENV, "production") // 判断开发环境，true为生产环境即线上，false为开发环境
const baseURL = isPro ? "https://master.huashushop.com/master/" : "/master"

// 使用自定义的配置文件发送请求
const instance = axios.create({
    baseURL: baseURL,
    timeout: 200000,
})

// http 请求拦截器
instance.interceptors.request.use(
    (config) => {
        let token = localStorage.getItem("token")
        let bosid = localStorage.getItem("bosid")
        if (token) {
            config.headers["Authorization"] = token
            config.headers["hsy-bosid"] = bosid
        }
        return config
    },
    (err) => {
        return Promise.reject(err)
    }
)

// http 响应拦截器
instance.interceptors.response.use(
    (response) => {
        let token = response.headers.authorization || response.headers.Authorization
        if (token) {
            localStorage.setItem("token", token)
        }
        // let code = response.data.code;
        return response
    },
    (error) => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    ElMessage({
                        message: "登录失效，请重新登录！",
                        type: "error",
                        duration: 1000,
                    })
                    router.replace("/")
                    break
                case 403:
                    ElMessage({
                        message: error.response.data,
                        type: "error",
                        duration: 1500,
                    })
                    // router.push("/Page403")
                    break;
                case 422:
                case 405:
                case 500:
                    let msgs = typeof (error.response.data) === 'string' ? error.response.data : error.response.data.message
                    ElMessage({
                        message: `${error.response.status}：${msgs}`,
                        type: "error",
                        duration: 2500,
                    })
                    break
                default:
                    break;
            }
        }
        return Promise.reject(error)
    }
)

export default instance
